package fit.conceptmap.controller;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import fit.conceptmap.beans.JsonBean;
import fit.conceptmap.services.IDrawService;

@Controller
@SessionAttributes({"username", "role" })
public class DrawController {
	
	private static final Logger logger = Logger.getLogger(DrawController.class);
	
	@Autowired IDrawService drawService;
	
	
	/**
	 * When click Save button on UI:
	 * - If concept map is newly created, then create new concept, node, link, relationship.
	 * - If concept, node, link, relationship already exists, update them.
	 */
	@RequestMapping(value="/drawconceptmap", method=RequestMethod.POST, headers="Accept=application/json")
	@ResponseBody
	public JsonBean draw(@RequestBody JsonBean json, Model model, @ModelAttribute("username") String username) {
		if(drawService.addDraw(username, json))
			logger.info("Add successfull.");;
		return json;
	}
	
	/**
	 * Create new Concept Maps
	 */
	@RequestMapping(value="/addconceptmap", method=RequestMethod.POST, headers="Accept=application/json")
	@ResponseBody
	public JsonBean addConceptMaps(@RequestBody JsonBean json, Model model, @ModelAttribute("username") String username){
		if(drawService.addConceptMaps(username, json))
			logger.info("Add successfull.");;
		return json;
	}
	
	/**
	 * Get list Concept Maps
	 */
	@RequestMapping(value="/listconceptmap", method=RequestMethod.GET, headers="Accept=application/json")
	@ResponseBody
	public List<JsonBean> getListConceptMaps(Model model, @ModelAttribute("username") String username) {
		return drawService.getListConcepmapByUsername(username);
	}
	
	/**
	 * 
	 * @param conceptMapsId get from client
	 * @return JsonBean
	 */
	@RequestMapping(value="/loadconceptmap/{conceptMapsId}", method=RequestMethod.GET)
	@ResponseBody
	public JsonBean loadDraw(Model model, @PathVariable String conceptMapsId) {
		return drawService.getJsonBean(conceptMapsId);
	}
}
